const fs = require('fs');
const path = require('path');
const config = require('./config');
const chalk = require('chalk');
const tupload = require('@tencent/tupload2');
const {cleanupMapComment} = require('./uploadSentry');
function getFiles(dir,fileList){
  const files = fs.readdirSync(dir);
  files.forEach(file=>{
    const filePath = path.join(dir,file);
    if(fs.lstatSync(filePath).isDirectory()){
      getFiles(filePath,fileList);
    }else if(file.search(/^\.|\.html$/)<0){
      fileList.push(filePath);
      cleanupMapComment(filePath);
    }
  });
}
module.exports = async function(){
  console.log(chalk.yellow('正在上传静态资源...'));
  const fileList = [];
  const promiseAll = [];
  getFiles(config.projectDist,fileList);
  fileList.forEach(file=>{
    promiseAll.push(
      tupload.upload(file, `${config.tupload.baseUrl}${path.relative(config.projectDist,file)}`, config.tupload)
      .then((res) => {
        if (Number(res.ret) !== 0) {
          throw new Error(`${file} =>  上传失败：${res.msg}`);
        }
      })
    );
  });
  await Promise.all(promiseAll);
  console.log(chalk.green(`文件夹："${path.relative(path.join(config.projectPath,'..'),config.projectDist)}"内所有静态资源上传完成`));
}
